package com.example.easypoi.demo1.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.util.PoiValidationUtil;
import com.alibaba.fastjson2.JSONObject;
import com.example.easypoi.demo1.entity.TalentUserInputEntity;
import com.example.easypoi.demo1.handler.TalentImportVerifyHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@RestController
public class EasyPoiTestController {
    @Resource
    private TalentImportVerifyHandler talentImportVerifyHandler;

    @PostMapping("/upload")
    public Boolean upload(@RequestPart("file") MultipartFile multipartFile) throws Exception {
        ImportParams params = new ImportParams();
        // 表头设置为2行
        params.setHeadRows(2);
        // 标题行设置为0行，默认是0，可以不设置
        params.setTitleRows(1);
        // 开启Excel校验
        params.setNeedVerify(true);
        params.setVerifyHandler(talentImportVerifyHandler);
        ExcelImportResult<TalentUserInputEntity> result = ExcelImportUtil.importExcelMore(multipartFile.getInputStream(),
                TalentUserInputEntity.class, params);
        System.out.println("是否校验失败: " + result.isVerifyFail());
        System.out.println("校验失败的集合:" + JSONObject.toJSONString(result.getFailList()));
        System.out.println("校验通过的集合:" + JSONObject.toJSONString(result.getList()));
        for (TalentUserInputEntity entity : result.getFailList()) {
            int line = entity.getRowNum() + 1;
            String msg = "第" + line + "行的错误是：" + entity.getErrorMsg();
            System.out.println(msg);
        }
        return true;
    }

    @PostMapping("/downloadForVerify")
    public void downloadForVerify(HttpServletResponse response) throws IOException {
        // 设置 Excel 导出参数
        ExportParams exportParams = new ExportParams("签名报备资料", "sheet1");
        ArrayList<TalentUserInputEntity> talentUsers = new ArrayList<>();
        getTalentUserInputEntity(talentUsers);
        try (Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TalentUserInputEntity.class, talentUsers)) {
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            String encodedFileName = URLEncoder.encode("签名报备资料模板.xls", "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
            workbook.write(response.getOutputStream());
        }

    }

    private static void getTalentUserInputEntity(List<TalentUserInputEntity> talentUsers) {
        TalentUserInputEntity talentUserInputEntity = new TalentUserInputEntity();
        talentUserInputEntity.setName("张三");
        talentUserInputEntity.setGenderStr("1");
        talentUserInputEntity.setPhone("15389046977");
        talentUserInputEntity.setNational("中国");
        talentUserInputEntity.setJobsName("工人");
        talentUserInputEntity.setSalaryStr("3");
        talentUserInputEntity.setWorkArea("美国");
        talentUserInputEntity.setExperienceList(null);
        talentUserInputEntity.setEducationList(null);
        talentUsers.add(talentUserInputEntity);
    }

    @PostMapping("/uploadForVerifyCollection")
    public Boolean uploadForVerifyCollection(@RequestPart("file") MultipartFile multipartFile) throws Exception {
        ImportParams params = new ImportParams();
        // 表头设置为2行
        params.setHeadRows(2);
        // 标题行设置为0行，默认是0，可以不设置
        params.setTitleRows(1);
        // 开启Excel校验
        params.setNeedVerify(true);
        params.setVerifyHandler(talentImportVerifyHandler);
        ExcelImportResult<TalentUserInputEntity> result = ExcelImportUtil.importExcelMore(multipartFile.getInputStream(),
                TalentUserInputEntity.class, params);
        System.out.println("是否校验失败: " + result.isVerifyFail());
        System.out.println("校验失败的集合:" + JSONObject.toJSONString(result.getFailList()));
        System.out.println("校验通过的集合:" + JSONObject.toJSONString(result.getList()));

        // 合并结果集
        List<TalentUserInputEntity> resultList = new ArrayList<>();
        resultList.addAll(result.getFailList());
        resultList.addAll(result.getList());
        for (TalentUserInputEntity inputEntity : resultList) {
            StringJoiner joiner = new StringJoiner(",");
            joiner.add(inputEntity.getErrorMsg());
            // 校验Collection的元素
            inputEntity.getExperienceList().forEach(e -> verify(joiner, e));
            inputEntity.getEducationList().forEach(e -> verify(joiner, e));
            inputEntity.setErrorMsg(joiner.toString());
        }

        for (TalentUserInputEntity entity : result.getFailList()) {
            int line = entity.getRowNum() + 1;
            String msg = "第" + line + "行的错误是：" + entity.getErrorMsg();
            System.out.println(msg);
        }
        return true;
    }

    private void verify(StringJoiner joiner, Object object) {
        String validationMsg = PoiValidationUtil.validation(object, null);
        if (StringUtils.isNotEmpty(validationMsg)) {
            joiner.add(validationMsg);
        }
    }


}
